package com.example.gokchinesefoodmappcdev.filter;

import com.example.gokchinesefoodmappcdev.exception.ValidateCodeException;
import com.example.gokchinesefoodmappcdev.handler.LoginFailHandler;
import com.example.gokchinesefoodmappcdev.util.TimeCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @author:chen jianbin
 * @date: 2022/11/21
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Autowired
    LoginFailHandler loginFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        try {
            //1.只是对登录请求，才有验证码验证

            if(("/rest/auth").equals(request.getRequestURI()) && request.getMethod().equals("POST")){
                //取出用户提交的验证码
                String imageCode = request.getParameter("imageCode");
                String codeId = request.getParameter("codeId");

                System.out.println("codeId:---------------"+codeId);
                //根据前端传的codeId从缓存取出validateCode
                String validateCode = TimeCacheUtil.get(codeId);
                System.out.println(validateCode);

                if (imageCode == null || "".equals(imageCode)){
                    throw new ValidateCodeException("验证码不能为空");
                }

                if(validateCode==null){
                    throw new ValidateCodeException("验证码失效");
                }

                if(!validateCode.equals(imageCode)){
                    throw new ValidateCodeException("验证码错误");
                }

                //验证成功移除缓存中的验证码
                TimeCacheUtil.remove(codeId);

            }

            filterChain.doFilter(request,response);
        } catch (AuthenticationException e) {
            loginFailHandler.onAuthenticationFailure(request,response,e);
        }
    }
}
